/*
 * LogPool.java	2009/04/04
 *
 * Copyright 2009 Web & Zen Multimedia, All rights reserved.
 * Use is subject to license terms.
 */
package it.wzm.lightweightlog;

import java.lang.reflect.Constructor;
import java.util.Properties;

/**
 * This class holds all the created Log with a specific name. It also manage the lifecycle of a log and creation of new Log.
 * @author Leonardo Celati
 */
abstract class LogPool<E extends Log> extends LightweightlogObject  {

	/** As required by serializiation */
	private static final long serialVersionUID = 3075249701579637111L;
		/** The log classname */
	private final String logClassname; 
	
	/** Initialize Pool from a given set of properties */
	LogPool(Properties p) {
		// calling super constructor with a default name...
		super("logpool",p);
		
		// initialize our constructor for log...
        try {
        	// search for classname in property file...
            logClassname = p.getProperty(Constant.PROP_ROOT + "log.classname", Constant.DEFAULT_LOG);
            
        } catch (RuntimeException e) {
        	this.setStatus(Status.FAILURE);
            throw new LightweightlogInitializationException(e);
        } catch (Exception e) {
        	this.setStatus(Status.FAILURE);
            throw new LightweightlogInitializationException(e);
        }
	}
	
	/**
	 * Add a log to pool 
	 * @param e Log to add
	 * @return true/false if been added
	 */
	abstract boolean add(E e);
	
	/**
	 * Find a log by its name
	 * @param classname the name to look for
	 * @return a valid log if found
	 */
	protected abstract E findByClassname(String classname);
		
	/**
	 * Create a log
	 * @return a valid Log
	 */
	protected final E createLog(String classname) {
		
		try {
			// init our log...
			Class<?> c = Class.forName(logClassname.trim());
			Constructor cst = c.getConstructor(String.class, Properties.class);
			return (E)cst.newInstance(classname, this.getProperties());
			
		} catch (RuntimeException e) {
			return null;
		} catch (Exception e) {
			return null;
		}
	}			
	
	/**
	 * Create a log with a specific name or return if exists
	 * @param classname the name of the log
	 * @return a valid log
	 */
	abstract E getInstance(String classname);
	
	/**
	 * Get the size of the pool
	 * @return the pool size
	 */
	public abstract int size();

}
